<template>
  <!--  可行内编辑的表格组件  -->
  <el-table
      :data="tableData"
      :border="border"
      style="width: 100%"
      @cell-click="handleCellClick"
      v-bind="$attrs"
      class="upgradeTable"
      :row-class-name="'upgradeRow'"
  >
    <!--  列配置  -->
    <el-table-column
        v-for="item in columns"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
    >
      <!--   操作按钮配置   -->
      <template
          #default="scope"
          v-if="item.operate"
      >
        <span v-for="btn in item.children">
          <el-button
              v-if="!isShowBtn && isShowEditBtn(btn.method, scope.row, btn)"
              :key="btn.prop"
              :type="btn.type"
              :plain="btn.plain"
              :link="btn.link"
              @click="btnClick(btn.method, btn, scope.row, scope.$index)"
          >
            {{ btn.label }}
          </el-button>
        </span>
      </template>

      <template
          #default="{ row, column, rowIndex, columnIndex }"
          v-else
      >
        <!--   isDetile是否是详情类的查看↓   -->
        <div v-if="!isDetile">
          <!--    isBorder是否全局开启编辑状态↓      -->
          <div v-if="isBorder">
            <!-- <span v-if="!item.isEdit">{{ row[item.prop] }}</span> -->

            <!--      有类型      -->
            <div
                v-if="typeof item.inputType !== 'undefined'"
            >
              <el-input
                  v-if="
                  item.inputType !== 'date' &&
                  item.inputType !== 'dateTime' &&
                  item.inputType !== 'textarea' &&
                  item.inputType !== 'select' &&
                  item.inputType !== 'numberInput' &&
                  !item.isEdit
                "
                  :ref="`input_${row[tableKey]}_${item.prop}`"
                  v-model="row[item.prop]"
                  @blur="handleBlur(row, item.prop)"
              />

              <el-input
                  autosize
                  type="textarea"
                  v-if="item.inputType == 'textarea' && !item.isEdit"
                  :ref="`input_${row[tableKey]}_${item.prop}`"
                  v-model="row[item.prop]"
                  @blur="handleBlur(row, item.prop)"
              />

              <el-input-number
                  v-if="item.inputType == 'numberInput' && !item.isEdit"
                  :ref="`input_${row[tableKey]}_${item.prop}`"
                  v-model="row[item.prop]"
                  style="width: 100%"
                  :min="0"
                  @blur="handleBlur(row, item.prop)"
              />

              <el-date-picker
                  :value-format="item.format ? item.format : 'YYYY-MM-DD'"
                  v-else-if="item.inputType === 'date' && !item.isEdit"
                  placeholder="请选择日期"
                  :disabled-date="disabledBeforeDate"
                  v-model="row[item.prop]"
              ></el-date-picker>

              <el-date-picker
                  :value-format="item.format ? item.format : 'YYYY-MM-DD HH:mm:ss'"
                  v-else-if="item.inputType === 'dateTime' && !item.isEdit"
                  placeholder="请选择日期时间"
                  v-model="row[item.prop]"
              ></el-date-picker>

              <el-select
                  :ref="`input_${row[tableKey]}_${item.prop}`"
                  v-model="row[item.prop]"
                  :filterable="item.filterable"
                  :multiple="item.multiple"
                  v-else-if="item.inputType === 'select' && !item.isEdit"
                  @blur="handleBlur(row, item.prop)"
              >
                <el-option
                    v-for="optObj in item.options"
                    :key="optObj.value"
                    :label="optObj.label"
                    :value="optObj.value"
                />
              </el-select>
              <!--     不是详情查看、开启了全局编辑、 有类型且当前数据项是不可被编辑的        -->
              <span v-if="item.isEdit">{{ row[item.prop] }}</span>
            </div>

            <!--    无类型时默认使用input↓        -->
            <div v-else>
              <el-input
                  :ref="`input_${row[tableKey]}_${item.prop}`"
                  v-model="row[item.prop]"
              />
            </div>
          </div>
          <!--  clickRowEdit为true时， 不开启全局编辑状态，手动点击按钮开启行编辑↓     -->
          <div v-if="!isBorder && clickRowEdit">
            <el-input
                v-if="
                editableCell === row[tableKey] &&
                item.inputType !== 'date' &&
                item.inputType !== 'dateTime' &&
                item.inputType !== 'textarea' &&
                item.inputType !== 'select' &&
                !item.isEdit
              "
                :ref="`input_${row[tableKey]}_${item.prop}`"
                v-model="row[item.prop]"
            />

            <el-input
                autosize
                type="textarea"
                v-else-if="
                item.inputType == 'textarea'&&
                editableCell === row[tableKey] &&
                !item.isEdit
                "
                :ref="`input_${row[tableKey]}_${item.prop}`"
                v-model="row[item.prop]"
            />

            <el-date-picker
                :value-format="item.format ? item.format : 'YYYY-MM-DD'"
                v-else-if="
                editableCell === row[tableKey] &&
                item.inputType === 'date' &&
                !item.isEdit
              "
                placeholder="请选择日期"
                :disabled-date="disabledBeforeDate"
                v-model="row[item.prop]"
            >
            </el-date-picker>
            <el-date-picker
                :value-format="item.format ? item.format : 'YYYY-MM-DD HH:mm:ss'"
                v-else-if="
                editableCell === row[tableKey] &&
                item.inputType === 'dateTime' &&
                !item.isEdit
              "
                placeholder="请选择日期时间"
                v-model="row[item.prop]"
            >
            </el-date-picker>
            <el-select
                v-model="row[item.prop]"
                v-else-if="
                editableCell === row[tableKey] &&
                item.inputType === 'select' &&
                !item.isEdit
              ">
              <el-option
                  v-for="optObj in item.options"
                  :key="optObj.value"
                  :label="optObj.label"
                  :value="optObj.value"
              />
            </el-select>
            <span v-else-if="editableCell !== item[tableKey] && item.inputType == 'select'"
            >
                {{
                item.options.findIndex((opt) => {
                  return opt.value === row[item.prop];
                }) > -1 ? item.options[
                    item.options.findIndex((opt) => {
                      return opt.value === row[item.prop];
                    })
                    ].label : selectValueNull
              }}
            </span>

            <span v-else-if="editableCell !== item[tableKey] && item.inputType !== 'select'"
            >
              {{ row[item.prop] }}
            </span>
          </div>

          <!--    不开启全局编辑的状态↓ 点击单元格开启单元格编辑     -->
          <div v-if="!isBorder && !clickRowEdit">
            <el-input
                v-if="
                editableCell === row[tableKey] &&
                editableColumn === item.prop &&
                item.inputType !== 'date' &&
                item.inputType !== 'dateTime' &&
                item.inputType !== 'textarea' &&
                item.inputType !== 'select' &&
                !item.isEdit
              "
                :ref="`input_${row[tableKey]}_${item.prop}`"
                v-model="row[item.prop]"
                @blur="handleBlur(row, item.prop)"
            />

            <el-input
                autosize
                type="textarea"
                v-if="
                item.inputType == 'textarea' &&
                 !item.isEdit &&
                 editableCell === row[tableKey] &&
                 editableColumn === item.prop"
                :ref="`input_${row[tableKey]}_${item.prop}`"
                v-model="row[item.prop]"
                @blur="handleBlur(row, item.prop)"
            />

            <el-date-picker
                :value-format="item.format ? item.format : 'YYYY-MM-DD'"
                v-else-if="
                editableCell === row[tableKey] &&
                editableColumn === item.prop &&
                item.inputType === 'date' &&
                !item.isEdit
              "
                placeholder="请选择日期"
                :disabled-date="disabledBeforeDate"
                v-model="row[item.prop]"
            >
            </el-date-picker>
            <el-date-picker
                :value-format="item.format ? item.format : 'YYYY-MM-DD HH:mm:ss'"
                v-else-if="
                editableCell === row[tableKey] &&
                editableColumn === item.prop &&
                item.inputType === 'dateTime' &&
                !item.isEdit
              "
                placeholder="请选择日期时间"
                v-model="row[item.prop]"
            >
            </el-date-picker>
            <el-select
                v-model="row[item.prop]"
                v-else-if="
                editableCell === row[tableKey] &&
                editableColumn === item.prop &&
                item.inputType === 'select' &&
                !item.isEdit
              ">
              <el-option
                  v-for="optObj in item.options"
                  :key="optObj.value"
                  :label="optObj.label"
                  :value="optObj.value"
              />
            </el-select>
            <span v-else
                  @click.stop="handleCellClick(row, column, rowIndex, columnIndex)"
            >
              {{ row[item.prop] }}
            </span>
          </div>
        </div>
        <!--    是详情类的查看页面↓    -->
        <div v-else>
          <!--    不是select的类型的数据则只显示文字数据本身      -->
          <span
              v-if="item.inputType !== 'select'"
          >
            {{ row[item.prop] }}
          </span>
          <!--     如果是select数据需传入options属性，确保能匹配到数据显示     -->
          <span v-else>
            {{
              item.options.findIndex((opt) => {
                return opt.value === row[item.prop];
              }) > -1 ? item.options[
                  item.options.findIndex((opt) => {
                    return opt.value === row[item.prop];
                  })
                  ].label : selectValueNull
            }}
          </span>
        </div>
      </template>
      <!--   自定义插槽  slotName 属性必须为true -->
      <template
          #default="{ row, column }"
          v-if="item.slotName"
      >
        <slot
            :name="item.keyName"
            :column="column"
            :item="row"
        >
        </slot>
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup>
import {ref, watch} from "vue";
import {TableColumn, TableDataItem} from "@/views/components/table/ZTable/type.ts";

const props = defineProps({
  tableKey: {
    type: String,
    default: () => {
      return 'id'
    }
  },
  border: {
    type: Boolean,
    default: false,
  },
  tableData: {
    type: Array<TableDataItem>,
  },
  columns: {
    type: Array<TableColumn>,
  },
  isDetile: {
    type: Boolean,
    default: true,
  },
  immutable: {
    type: Boolean,
    default: true,
  },
  isBorder: {
    type: Boolean,
    default: true,
  },
  clickRowEdit: {
    type: Boolean,
    default: false,
  },
  isShowBtn: {
    type: Boolean,
    default: false,
  },
  startTime: {
    type: String,
  },
  weekEndTime: {
    type: String,
  },
  selectValueNull: {
    type: String,
    default: () => {
      return ''
    }
  },
  rowSubmit: {
    type: Boolean,
    default: false,
  }
});

// const tableData = ref([
//   {id: 1, name: 'John', age: 30},
//   {id: 2, name: 'Jane', age: 25},
//   // ... more data
// ]);

// const columns = ref([
//   {label: 'Name', prop: 'name'},
//   {label: 'Age', prop: 'age'},
//   // ... more columns
// ]);

const emits = defineEmits([
  "CellClick", "handleBlur", "rowSubmit",
  "deleteRow",
  "editRow",
  "detailRow",
  "infoRow",
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q"
]);

const isShowEditBtn = (method, row, btn) => {
  if (method === 'editRow') {
    // 默认状态
    if (btn['methodType'] === 'edit' && row[props.tableKey] !== editableCell.value) {
      return true
    } else if (btn['methodType'] && btn['methodType'] !== 'edit' && row[props.tableKey] === editableCell.value) {
      return true
    } else {
      return false
    }
  } else {
    return true
  }

}

const editableCell = ref<number | null>(null);
const editableColumn = ref<string | null>(null);

const handleCellClick = (
    row: { id: number },
    column: { property: string },
    rowIndex: number,
    columnIndex: number
) => {
  if (!props.isBorder && props.clickRowEdit) {
    return false
  }
  console.log(row[props.tableKey], column);
  editableCell.value = row[props.tableKey];
  editableColumn.value = column.property;
  emits("CellClick", row, column);
};

const handleBlur = (row: { [key: string]: any }, columnProp: string) => {
  // 在这里可以添加保存更改的逻辑
  editableCell.value = null;
  editableColumn.value = null;
  console.log(row);
  emits("handleBlur", row);
};

watch(() => editableCell.value, () => {
  emits('editRow', null, null, null);
})

const disabledBeforeDate = (date: Date) => {
  let start = new Date(props.startTime).getTime() - 86400000;
  let end = new Date(props.weekEndTime).getTime();
  return date.getTime() <= start || date.getTime() >= end;
};

const btnClick = (
    method:
        | "deleteRow"
        | "editRow"
        | "detailRow"
        | "infoRow"
        | "a"
        | "b"
        | "c"
        | "d"
        | "e"
        | "f"
        | "i"
        | "j"
        | "k"
        | "l"
        | "m"
        | "n"
        | "o"
        | "p"
        | "q",
    btn: Object,
    row: TableDataItem,
    index: number
) => {
  console.log("method: ", method);
  // 注意：这里我们假设除了 'deleteRow', 'editRow', 'detailRow', 'infoRow' 之外的事件不需要传递 row 和 index，
  // 但由于您的原始代码传递了这些参数，我保留了它们。如果某些事件不需要这些参数，您应该调整 emit 调用以匹配实际的事件处理器期望。
  if (props.clickRowEdit && method === "editRow") {
    editableCell.value = row[props.tableKey]
  }
  emits(method, row, index, btn['methodType']);
};

watch(() => props.rowSubmit, (newData) => {
  if (newData) {
    emits('rowSubmit', false)
    editableCell.value = null
  }
})
</script>

<style lang="scss" scoped>
@import "@/assets/var";

.upgradeTable {
  overflow: auto;
  font-size: $--table-size;
  color: $--table-color;
  background: $--table-bg;
  //box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.5);

  & ::v-deep(.el-table__row.upgradeRow) {
    background: $--table-tr-bg;
    &:hover{
      color: $--table-row-hover-color;
    }
    //&.el-table__row{
    //  :hover{
    //    background: red;
    //  }
    //}
  }

  ::v-deep(.el-table__header-wrapper th) {
    /* 自定义表头样式 */
    & tr {
      background: $--table-th-bg;
    }

    background: $--table-th-bg;
    color: $--table-th-color;
    font-size: 14px;
  }
}
</style>
